import axios from 'axios'
import { Message, Loading } from 'element-ui'
const ConfigBaseURL = '/api' // 默认路径，这里也可以使用env来判断环境
let loadingInstance = null // 这里是loading
// 使用create方法创建axios实例
export const Service = axios.create({
  withCredentials: true,
  timeout: 3000, // 请求超时时间
  baseURL: ConfigBaseURL,
  method: 'post',
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
// Service.defaults.withCredentials = true
// 添加请求拦截器
Service.interceptors.request.use(config => {
  loadingInstance = Loading.service({
    lock: true,
    text: 'loading...'
  })
  return config
})
// 添加响应拦截器
Service.interceptors.response.use(response => {
  loadingInstance.close()
  // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
  // 否则的话抛出错误
  if (response.status === 200) {
    return Promise.resolve(response.data)
  } else {
    return Promise.reject(response.data.msg)
  }
}, error => {
  const msg = error.msg !== undefined ? error.msg : ''
  Message({
    message: msg,
    type: 'error',
    duration: 3 * 1000
  })
  loadingInstance.close()
  return Promise.reject(error)
})

export const request = (data) => {
  return new Promise(resolve => {
    Service({
      url: data.url,
      method: data.method,
      data: data.data,
      params: data.params
    }).then(res => {
      // eslint-disable-next-line no-undef
      resolve(res)
    }).catch(err => {
      console.log('回调', err)
      Message({
        message: err,
        type: 'error',
        duration: 3 * 1000
      })
    })
  })
}

export const upload = (url, data) => {
  return new Promise(resolve => {
    axios.post(ConfigBaseURL + url, data, {
      'Content-type': 'multipart/form-data'
    }).then(res => {
      // eslint-disable-next-line no-undef
      resolve(res)
    }).catch(err => {
      console.log('回调', err)
      Message({
        message: err,
        type: 'error',
        duration: 3 * 1000
      })
    })
  })
}
